import codecs


def fname(a, b, sentence):
    if b[0] == 'null':
        a.insert(0, '$T$')
    else:
        c = []
        for seg in range(len(b)):
            for seg1 in range(len(a)):
                if b[seg] == a[seg1]:
                    c.append(seg1)
        for seg2 in range(len(a)):
            if seg2 in c:
                a[seg2] = '$T$'
        for i in range(c[len(c) - 1], c[0], -1):
            a.pop(i)

    m = ' '.join(a)
    n = ' '.join(b)
    sentence.append([n, m])
    return sentence


def write(sentence, output_file):
    with open(output_file, 'a', encoding='utf-8') as f:
        for seg in range(len(sentence)):
            f.write(sentence[seg][0])
            f.write("\n")
            f.write(sentence[seg][1])
            f.write("\n")


if __name__ == "__main__":
    sentence = 'data/14res/sentence_test_1.txt'
    term = 'data/14res/generate_target_test.txt'
    # polarity = 'data/14lap/test/polarity.txt'
    output_file = 'data/14res/origin_sentence_test.txt'

    fsen = codecs.open(sentence, 'r', 'utf-8')
    fterm = codecs.open(term, 'r', 'utf-8')

    sentence = []
    for text, term in zip(fsen, fterm):
        text = text.strip()
        term = term.strip().split()
        words = text.split()
        result = fname(words, term, sentence)
    write(result, output_file)